require(['zTreeCheckbox', 'grid', 'tableTree'], function () {
    //========================================================变量
    var userInfo = commonFun.execParentMethod("getUserInfo");					//当前用户信息
    // 如果是最高管理员登录,可以让其看到所属公司
    var isAdminRole = userInfo.isAdminRole;										//是否最高管理员
    var funcId = "", 															//功能权限id
        trNode, 																//角色树节点
        ztree = null,															//功能权限树
        $fieldsTab = $("#fieldsTab"),
        currentMenu,//高亮选中的label
        $sysRoleTree = $("#sysRoleTree"),										//角色树
        setting;																//角色树设置

    function initElements() {
        //初始化权限树设置
        setting = {
            check: {
                enable: true,
                chkboxType: {
                    "Y": "ps",
                    "N": "ps"
                }
            },
            data: {
                keep: {
                    leaf: false,
                    parent: true
                },
                key: {
                    name: "name"
                },
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "funcId",
                    rootPid: null
                }
            },
            view: {
                showIcon: false
            },
            callback: {
                onClick: function (event, treeId, treeNode, clickFlag) {
                    trNode = treeNode;
                    // 显示对应的字段权限配置表
                    if (treeNode.type === "3") {
                        funcId = treeNode.id;
                    } else {
                        funcId = "";
                    }
                }
            }
        }
        // initFieldsTabGrid();
        //初始化角色树
        initSysRoleTree();
    }


    /**
     * 获得根节点并选中根节点
     */
    function getAndSelectRootNode() {
        var node = sysRoleTreeObj.getNodesByFilter(function (node) {
            return node.level == 0;
        }, true);
        sysRoleTreeObj.selectNode(node, false);
        sysRoleTreeClick(null, node.id, node, true);
    }

    /**
     * 点击树节点
     * @param event 事件
     * @param treeId ztree节点id
     * @param treeNode ztree节点
     * @param clickFlag 点击标识
     */
    function sysRoleTreeClick(event, treeId, treeNode, clickFlag) {
        $("#corpId").val(treeNode.corpId);
        $("#roleId").val(treeNode.id);
        $("#level").val(treeNode.level);
        $("#opr").val("clickTree");
        // 自己的角色不允许修改
        $.ajaxExt({
            async: true,
            url: "/sysAuthorityFunc/getFuncDataResList.htm",
            data: {
                "roleId": treeNode.id,
                "level": treeNode.level,
                "roleType" : userInfo.roleType
            }
        }).done(function (data) {
            tableTree.init(data);
            currentMenu = null;
            reloadTree();
        });
    }

    function reloadTree() {
        $.ajaxExt({
            async: true,
            url: "/sysAuthorityFunc/getCheckedFuncData.htm",
            data: {
                "roleId": $("#roleId").val()
            }
        }).done(function (data) {
            // 全部取消勾选
            // ztree.checkAllNodes(false);
            // 根据读取数据设置勾选
            if (data) {
                tableTree.setData(data);
                // $.each(data, function (i, ctx) {
                //     var node = ztree.getNodeByParam("id", ctx.id);
                //     if (node) {
                //         ztree.checkNode(node);
                //     }
                // });
            }
        });
    }

    /**
     * 获得节点数据，并且生成左侧的树
     */
    function initSysRoleTree() {
        $.ajaxExt({
            async: true,
            url: "/sysRole/getSysRoleByName.htm"
        }).done(function (data) {
            if (!data) {
                data = [];
            }
            // 树的参数配置
            var setting = {
                data: {
                    key: {
                        name: "name"
                    },
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "parentRoleId",
                        rootPId: 0
                    }
                },
                view: {
                    showIcon: true
                },
                callback: {
                    onClick: sysRoleTreeClick
                }
            };
            // 生成树
            sysRoleTreeObj = $sysRoleTree.createTree(setting, data, {search: $('#search-text')});
            sysRoleTreeObj.setting.view.expandSpeed = "";
            sysRoleTreeObj.expandAll(true);
            sysRoleTreeObj.setting.view.expandSpeed = "fast";
            getAndSelectRootNode();// 选中根节点，触发事件
        });
    }


    // 点击保存《功能权限和字段权限的分配信息》
    $("#saveAuthority").click(function () {
        var funcParams = tableTree.getData().funcIds,
            buttonParams = tableTree.getData().buttonIds;
        $.ajaxExt({
            url: "/sysAuthorityFunc/saveFuncAuthority.htm",
            async: true,
            loadMask:true,
            data: {
                "funcIds": funcParams,
                "buttonIds": buttonParams,
                // "fieldIds": fieldIds,
                "roleId": $("#roleId").val(),
                "ufuncId": funcId
            }
        }).done(function () {
            $.messager.alert("保存", "保存成功!", "msg",
                function () {
                    // 重新载入ztree
                    reloadTree();
                    //更新功能权限
                    commonFun.refreshFuncAuth();
                });
        });
    });
    // 全选事件
    // $("#chkAll").on("click", function () {
    //     ztree.checkAllNodes(true);
    // });
    // 反向全选事件
    // $("#unchkAll").on("click", function () {
    //     ztree.checkAllNodes(false);
    // });


    function resize() {
        var winHeight = $(window).height();
        //设置功能权限树高和宽
        $('#tree').css({
            height: winHeight - 111
        });
        //设置角色树高度
        $sysRoleTree.height(winHeight - 55);
        $("#left").height(winHeight);

        $("#right").height(winHeight-68);
    }

    $(window).on('resize', resize).trigger('resize');

    initElements();

    $('#searchMenu').on('keyup', function (e) {
        var val = $(this).val().trim();
        if (e.keyCode === 13 && val) {//回车
            var $label = $('#container label').not('.dropdown-label').removeClass('high-light');
            if (val) {
                // debugger;
                var $highLight = $label.filter(":contains('" + val + "')").addClass('high-light');
                if ($highLight.length) {
                    if (currentMenu) {
                        var _index = -1;
                        $.each($highLight, function (i, label) {
                            if (label === currentMenu.get(0)) {
                                _index = i;
                            }
                        });
                        currentMenu = $highLight.eq(_index >= ($highLight.length - 1) ? 0 : (_index + 1));
                    } else {
                        currentMenu = $highLight.eq(0);
                    }
                    scrollToElement(currentMenu);
                }
            } else {
                currentMenu = null;
            }
        }
    });

    function scrollToElement(el) {
        var $parent = $(el).closest('.item-wrap');
        if (!$parent.hasClass('active')) {
            $('.slide-btn3', $parent).trigger('click');
        }
        var offset = $(el).offset();
        $("#right").scrollTop(offset.top - 68 + $("#right").scrollTop());
    }
});
